﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
using System.Collections;
using System.Data;

namespace DAO
{
    public class ChiTietGioHangDAO
    {
        private DataProvider provider;

        public ChiTietGioHangDAO()
        {
            provider = new DataProvider();
        }

        public int ThemChiTietGioHang(ChiTietGioHangDTO chiTietGioHang)
        {

            string sqlStatement = "INSERT INTO ChiTietGioHang(MaGioHang, MaSach, SoLuong) VALUES (" 
                + chiTietGioHang.MaGioHang + ", " + chiTietGioHang.MaSach + ", " + chiTietGioHang.SoLuong + ")";

            return provider.ExecuteNonQuery(sqlStatement);
        }

        public int CapNhatChiTietGioHang(ChiTietGioHangDTO chiTietGioHang)
        {
            string sqlStatement = "UPDATE ChiTietGioHang SET MaGioHang=" + chiTietGioHang.MaGioHang 
                + ", MaSach=" + chiTietGioHang.MaSach + ", SoLuong=" + chiTietGioHang.SoLuong 
                + " WHERE MaChiTietGioHang=" + chiTietGioHang.MaChiTietGioHang;
            
            return provider.ExecuteNonQuery(sqlStatement);
        }

        public int XoaChiTietGioHang(ChiTietGioHangDTO chiTietGioHang)
        {
            string sqlStatement = "DELETE FROM ChiTietGioHang WHERE MaChiTietGioHang=" + chiTietGioHang.MaChiTietGioHang;

            return provider.ExecuteNonQuery(sqlStatement);
        }

        public ArrayList LayChiTietGioHangTheoMaGioHang(int maGioHang)
        {
            ArrayList arrChiTietGioHang = new ArrayList();
            try
            {
                string query = "SELECT * FROM ChiTietGioHang WHERE MaGioHang=" + maGioHang;
                DataTable dt = new DataTable();
                dt = provider.ExecuteQuery(query);

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    ChiTietGioHangDTO item = new ChiTietGioHangDTO();

                    item.MaChiTietGioHang = int.Parse(dt.Rows[i].ItemArray[0].ToString());
                    item.MaGioHang = int.Parse(dt.Rows[i].ItemArray[1].ToString());
                    item.MaSach = int.Parse(dt.Rows[i].ItemArray[2].ToString());
                    item.SoLuong = int.Parse(dt.Rows[i].ItemArray[3].ToString());

                    arrChiTietGioHang.Add(item);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error: " + ex.Message);
            }
            return arrChiTietGioHang;
        }
    }
}
